<template>
  <view class="container">
    <!-- navbar -->
    <FilterNavbar
      class="filte-navbar"
      :showBackIcon="false"
      :queryParam="queryParam"
      :searchList="searchList"
      @confirm="filterConfirm"
      @rightClick="rightClickFn"
      swtichPage
    >
      <template #center>
        <OrderTabs :permission="permission" actived-tab="short-order" @change="orderTabsChange" />
      </template>
    </FilterNavbar>
    <!-- 顶部筛选 -->
    <order-filter ref="orderTabsRef" type="short-order" @change="onOrderFilterChange" />
    <!-- 列表 -->
    <view class="">
      <view class="record-list">
        <order-item
          v-for="record in dataSource"
          :record="record"
          :employeeId="adminEmployeeId"
          :isAdminRole="isAdminRole"
          :key="record.id"
          @ok="hotUpdate(record)"
          @editStaffFn="editStaffFn"
          @editLesseeSuccessFn="
            (info) => {
              editLesseeSuccessFn(record, info)
            }
          "
        />
        <!-- 加载结束列表为空时展示 -->
        <ve-empty v-if="dataSource.length == 0 && loadStatus == 'nomore'"></ve-empty>
        <!-- 底部加载状态 -->
        <ve-load-more v-else :status="loadStatus" bgColor="#F7F7F9"></ve-load-more>
        <!-- 解决最后一条数据，点不到操作 -->
        <view style="height: 20vh" v-if="dataSource.length > 0"></view>
      </view>
    </view>
    <!-- 编辑交还车人 -->
    <selectorModal ref="selectorModalRef" @change="onConfirmStaff" @close="onCloseStaff" />
    <ve-toast ref="toastRef"></ve-toast>
  </view>
</template>

<script setup>
  import selectorModal from '@/components/remote-select/SelectorModal.vue'
  import FilterNavbar from '@/components/FilterNavbar'
  import orderItem from './components/order-item/orderItem.vue'
  import OrderFilter from '../components/order-filter'
  import OrderTabs from '../components/order-filter/order-tabs.vue'

  import { ref, computed, provide, onMounted } from 'vue'
  import { usePageDict } from '@/hooks/useDict'
  import useList from '@/hooks/useList'
  import { findStatisticsAPI, editGiveReturnStaffAPI } from '@/api/order/sOrder'
  import { http } from '@/utils/http'
  import { listStore } from '@/stores'
  import { updateUser } from '@/api/common/login'
  import { getSysParams } from '@/api/common'

  const emits = defineEmits(['tabClicked', 'toTop', 'popupVisible'])
  let dict = usePageDict('shortOrderDict')

  const channelList = ref([])
  const orderTabsRef = ref()
  const props = defineProps({
    permission: Object,
  })

  // 查询参数
  let queryParam = listStore().sOrderQueryParam
  provide('queryParam', queryParam)
  const { resetRefresh, reachBottom, loadData, scrollTop, loadStatus, refreshStatus, dataSource, updateHotUpdateFlag } = useList(
    '/V5/sOrder/pageList',
    queryParam,
  )
  // 长短租订单tabs切换
  const orderTabsChange = (type) => {
    emits('tabClicked', type)
  }
  // 点击筛选
  const rightClickFn = () => {
    orderTabsRef.value.closePopupLabel()
  }
  const filterConfirm = (val) => {
    Object.assign(queryParam, val)
    initFectch()
  }
  // 筛选 type:类型（排序 状态 关键字 标签)
  const onOrderFilterChange = (type) => {
    initFectch(type)
  }
  // 获取 tabs num
  const getTabsNum = (param) => {
    let tabsParam = { ...param }
    delete tabsParam.orderStatus
    findStatisticsAPI(tabsParam).then((res) => {
      const result = res.result
      orderTabsRef.value.updateTabsNum(result)
    })
  }
  // 获取 labels num
  const getLabelsNum = (param) => {
    findStatisticsAPI(param).then((res) => {
      const result = res.result
      orderTabsRef.value.updateLabelsnum(result)
    })
  }
  // 查询角标
  const fetchBadgeNum = (operateType) => {
    let _param = {
      ...queryParam,
      orderLabels: undefined,
    }
    if (!operateType || ['orderKeywords'].includes(operateType)) {
      // tab 角标
      getTabsNum(_param)
    }
    if (!operateType || ['orderKeywords', 'orderStatus', 'orderSort'].includes(operateType)) {
      // labels 角标
      getLabelsNum(_param)
    }
  }
  // 编辑交还车人
  const selectorModalRef = ref()
  // 操作的是交车 or 还车人
  const selectorStaffType = ref()
  const selectorStaffRecord = ref()
  const editStaffFn = (type, record) => {
    selectorStaffType.value = type
    selectorStaffRecord.value = record
    let oldId = type == 'giveStaff' ? record.giveStaffId : record.returnStaffId
    let siteId = type == 'giveStaff' ? record.siteId : record.returnSiteId
    // 交还车人姓名
    let staffName = type == 'giveStaff' ? record.giveStaffName : record.returnStaffName
    emits('popupVisible', true)
    selectorModalRef.value.open({
      type: 'reassignment_staff_list_multiple',
      value: oldId,
      config: {
        listPage: {
          title: type == 'giveStaff' ? '选择交车人' : '选择还车人',
        },
      },
      params: {
        oldId: oldId,
        siteIdList: [siteId],
        staffName: staffName,
      },
    })
  }
  // 编辑承租人完成，更新承租人信息
  const editLesseeSuccessFn = (record, newInfo) => {
    Object.assign(record, newInfo)
  }
  // 交还车人确认
  const onConfirmStaff = (staffId, staffName, staffOption) => {
    const record = selectorStaffRecord.value
    const param = {
      id: record.id,
      giveStaffId: record.giveStaffId,
      returnStaffId: record.returnStaffId,
    }
    if (selectorStaffType.value == 'giveStaff') {
      param.giveStaffId = staffId
    } else {
      param.returnStaffId = staffId
    }
    // 修改数据并局部修改列表的承租人
    editGiveReturnStaffAPI(param).then((res) => {
      if (selectorStaffType.value == 'giveStaff') {
        record.giveStaffId = staffId
        record.giveStaffName = staffName
      } else {
        record.returnStaffId = staffId
        record.returnStaffName = staffName
      }
    })
  }
  // 关闭交还车人弹窗
  const onCloseStaff = () => {
    emits('popupVisible', false)
  }
  const searchList = computed(() => {
    return [
      {
        prop: 'carModelId',
        label: '车型',
        type: 'remote-select',
        attrs: {
          type: 'carModel',
        },
      },
      {
        prop: 'orderSource',
        label: '订单来源',
        type: 'picker',
        attrs: {
          options: dict.orderSourceEnum,
        },
      },
      {
        prop: 'channelType',
        label: '订单渠道',
        type: 'picker',
        attrs: {
          options: channelList.value,
        },
      },
      {
        prop: 'orderAcquisitionType',
        label: '订单获取方式',
        type: 'remote-select',
        attrs: {
          type: 'order_acquisition',
        },
        config: {
          listPage: {
            title: '选择订单获取方式',
          },
        },
      },
      {
        prop: 'customLabelList',
        label: '自定义标签',
        type: 'remote-select',
        attrs: {
          type: 'customLabel',
          multiple: true,
        },
      },
      {
        prop: 'accountIdList',
        label: '运营主体',
        type: 'remote-select',
        attrs: {
          type: 'operatingSubject',
          multiple: true,
        },
      },
      {
        prop: 'siteIdList',
        label: '取车门店',
        type: 'remote-select',
        attrs: {
          type: 'site_all',
          // label: queryParam.siteId ? queryParam.siteName : undefined,
          multiple: true,
          params: { idList: queryParam.siteIdList },
        },
        config: {
          listPage: {
            title: '选择取车门店',
          },
        },
      },
      {
        prop: 'returnSiteIdList',
        label: '还车门店',
        type: 'remote-select',
        attrs: {
          type: 'site_all',
          multiple: true,
          params: { idList: queryParam.returnSiteIdList },
        },
        config: {
          listPage: {
            title: '选择还车门店',
          },
        },
      },
      {
        prop: 'giveStaffNameLike',
        label: '交车人',
      },
      {
        prop: 'replaceStaffName',
        label: '换车人',
      },
      {
        prop: 'returnStaffNameLike',
        label: '还车人',
      },
      {
        prop: ['startTimeBegin', 'startTimeEnd'],
        label: '预计取车时间',
        type: 'daterange-picker',
      },
      {
        prop: ['endTimeBegin', 'endTimeEnd'],
        label: '预计还车时间',
        type: 'daterange-picker',
      },
      {
        prop: ['actualStartTimeBegin', 'actualStartTimeEnd'],
        label: '实际取车时间',
        type: 'daterange-picker',
      },
      {
        prop: ['actualEndTimeBegin', 'actualEndTimeEnd'],
        label: '实际还车时间',
        type: 'daterange-picker',
      },
      {
        prop: ['createTimeBegin', 'createTimeEnd'],
        label: '创建时间',
        type: 'daterange-picker',
      },
      {
        prop: 'createUserNameLike',
        label: '创建人',
      },
      {
        prop: 'carDepositStatusList',
        label: '租车押金状态',
        type: 'remote-select',
        attrs: {
          type: 'dict',
          title: '选择租车押金状态',
          multiple: true, // 多选
          outData: dict.depositStatusEnum,
        },
      },
      {
        prop: 'illegalDepositStatusList',
        label: '违章押金状态',
        type: 'remote-select',
        attrs: {
          type: 'dict',
          title: '选择租车押金状态',
          multiple: true, // 多选
          outData: dict.depositStatusEnum,
        },
      },
    ]
  })

  // 代客下单
  const createOrderFn = () => {
    uni.navigateTo({ url: '/pages/order/short-order/form/index' })
  }

  // 热更新
  const hotUpdate = (record) => {
    fetchBadgeNum()
    // 获取订单详情
    http({
      method: 'POST',
      url: '/V5/sOrder/pageList',
      data: {
        pageNumber: 1,
        pageSize: 10,
        ...queryParam,
        // 用orderCode确认当前订单是够更改状态
        keywords: record.orderCode,
      },
    }).then((res) => {
      if (res.code == 200) {
        let { data, total } = res.result
        const index = dataSource.value.findIndex((item) => item.id == record.id)
        if (total > 0 && data.length > 0) {
          const newInfo = data[0]
          // 更新数据
          Object.assign(dataSource.value[index], newInfo)
        } else {
          // 删除数据
          dataSource.value.splice(index, 1)

          // 更新updateFlag
          updateHotUpdateFlag(true)
        }
      }
    })
  }

  const adminEmployeeId = ref()
  const isAdminRole = ref(false)
  // 更新用户信息 取权限用
  const updateUserInfo = () => {
    updateUser().then((res) => {
      adminEmployeeId.value = res.result.employeeId //空是admin
      let index = res.result.roles.findIndex((item) => {
        return item == '管理员'
      })
      isAdminRole.value = index != -1 ? true : false
    })
  }

  // 加载数据-全部刷新
  const toastRef = ref()
  const initFectch = (operateType) => {
    fetchBadgeNum(operateType)
    toastRef.value.showLoading()
    loadData(1).finally(() => {
      updateUserInfo()
      uni.stopPullDownRefresh()
      toastRef.value.hideLoading()
    })
    // 防止网络错误
    dict = usePageDict('shortOrderDict')
  }

  // 获取订单渠道
  const getChannelType = () => {
    getSysParams({ codeList: ['short_order_channel_type'], includeDisabled: 1 }).then((res) => {
      const result = res.result
      if (result) {
        channelList.value = result['short_order_channel_type'].map((item) => {
          return {
            label: item.name,
            value: item.value,
          }
        })
      }
    })
  }
  // 初始化
  onMounted(() => {
    initFectch()
    getChannelType()
  })

  defineExpose({
    initFectch,
    reachBottom,
    createOrderFn,
    hotUpdate,
  })
</script>

<style lang="less" scoped>
  .record-list {
    padding: 24rpx;
  }
  .order-type-list {
    display: flex;
    .order-type-item {
      width: 192rpx;
      height: 86rpx;
      text-align: center;
      font-size: 32rpx;
      color: #1d2129;
      position: relative;
      .order-type-item-border {
        width: 48rpx;
        height: 4rpx;
        background: transparent;
        border-radius: 4rpx;
        position: absolute;
        bottom: -2rpx;
        left: 50%;
        margin-left: -24rpx;
      }
    }
    .order-type-item-active {
      color: #3072f6;
      .order-type-item-border {
        background: #3072f6;
      }
    }
  }
  .filte-navbar {
    position: relative;
    z-index: 1000;
  }
</style>
